<#
.SYNOPSIS
    通过MAC地址在局域网内唤醒电脑
.DESCRIPTION
    此脚本提供图形界面，允许用户输入MAC地址并发送魔术包(Magic Packet)唤醒支持Wake-on-LAN的设备
.PARAMETER MacAddress
    目标设备的MAC地址，格式可以是"00:11:22:33:44:55"、"00-11-22-33-44-55"或"001122334455"
.PARAMETER GUI
    启动图形用户界面模式
.EXAMPLE
    .\Wake-On-LAN.ps1 -MacAddress "00:11:22:33:44:55"
.EXAMPLE
    .\Wake-On-LAN.ps1 -GUI
.NOTES
    确保目标设备已启用Wake-on-LAN功能，且在同一局域网内
#>

param (
    [Parameter(Mandatory=$false, Position=0, HelpMessage="请输入目标设备的MAC地址")]
    [string]$MacAddress,
    
    [Parameter(Mandatory=$false)]
    [switch]$GUI
)

function Send-WOL {
    param (
        [Parameter(Mandatory=$true)]
        [string]$MacAddress,
        
        [Parameter(Mandatory=$false)]
        [string]$InterfaceAlias = $null
    )

    # 验证MAC地址格式
    $MacRegex = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$|^([0-9A-Fa-f]{12})$"
    if (-not ($MacAddress -match $MacRegex)) {
        return "无效的MAC地址格式。请使用以下格式之一: 00:11:22:33:44:55, 00-11-22-33-44-55, 或 001122334455"
    }

    # 格式化MAC地址，移除所有分隔符
    $MacAddress = $MacAddress -replace "[:-]", ""
    
    try {
        # 创建魔术包
        # 魔术包由6个字节的0xFF，后跟目标MAC地址重复16次组成
        $MagicPacket = [byte[]](,0xFF * 6)
        
        # 将MAC地址转换为字节数组
        $MacBytes = [byte[]]::new(6)
        for ($i = 0; $i -lt 6; $i++) {
            $MacBytes[$i] = [Convert]::ToByte($MacAddress.Substring($i * 2, 2), 16)
        }
        
        # 将MAC地址重复16次添加到魔术包中
        for ($i = 0; $i -lt 16; $i++) {
            $MagicPacket += $MacBytes
        }
        
        # 获取本地网络接口信息
        $NetworkInterfaces = Get-NetIPAddress -AddressFamily IPv4 | Where-Object { $_.InterfaceAlias -notmatch 'Loopback' -and $_.IPAddress -ne '127.0.0.1' }
        
        # 如果指定了特定网络接口，则只使用该接口
        if ($InterfaceAlias) {
            $NetworkInterfaces = $NetworkInterfaces | Where-Object { $_.InterfaceAlias -eq $InterfaceAlias }
            if (-not $NetworkInterfaces) {
                return "找不到指定的网络接口: $InterfaceAlias"
            }
        }
        
        $successCount = 0
        $errorMessages = @()
        
        # 对每个网络接口发送魔术包
        foreach ($Interface in $NetworkInterfaces) {
            try {
                # 获取IP地址和子网掩码
                $IPAddress = $Interface.IPAddress
                $PrefixLength = $Interface.PrefixLength
                
                # 计算网络地址和广播地址
                $IPAddressBytes = [System.Net.IPAddress]::Parse($IPAddress).GetAddressBytes()
                $SubnetMaskBytes = [byte[]]::new(4)
                
                # 根据前缀长度计算子网掩码
                for ($i = 0; $i -lt 4; $i++) {
                    if ($PrefixLength -ge 8) {
                        $SubnetMaskBytes[$i] = 255
                        $PrefixLength -= 8
                    } elseif ($PrefixLength -gt 0) {
                        $SubnetMaskBytes[$i] = 256 - [Math]::Pow(2, 8 - $PrefixLength)
                        $PrefixLength = 0
                    } else {
                        $SubnetMaskBytes[$i] = 0
                    }
                }
                
                # 计算广播地址
                $BroadcastBytes = [byte[]]::new(4)
                for ($i = 0; $i -lt 4; $i++) {
                    $BroadcastBytes[$i] = $IPAddressBytes[$i] -bor (255 - $SubnetMaskBytes[$i])
                }
                
                $BroadcastAddress = [System.Net.IPAddress]::new($BroadcastBytes)
                
                # 创建UDP客户端
                $UdpClient = New-Object System.Net.Sockets.UdpClient
                
                # 绑定到本地接口
                $UdpClient.Client.SetSocketOption([System.Net.Sockets.SocketOptionLevel]::Socket, [System.Net.Sockets.SocketOptionName]::Broadcast, $true)
                $LocalEndPoint = New-Object System.Net.IPEndPoint([System.Net.IPAddress]::Parse($IPAddress), 0)
                $UdpClient.Client.Bind($LocalEndPoint)
                
                # 发送到广播地址
                $BroadcastEndPoint = New-Object System.Net.IPEndPoint($BroadcastAddress, 9)
                $BytesSent = $UdpClient.Send($MagicPacket, $MagicPacket.Length, $BroadcastEndPoint)
                $UdpClient.Close()
                
                $successCount++
            } catch {
                $errorMessages += "在接口 $($Interface.InterfaceAlias) ($($Interface.IPAddress)) 上发送失败: $_"
            }
        }
        
        # 尝试使用全网广播作为备用方案
        try {
            $UdpClient = New-Object System.Net.Sockets.UdpClient
            $UdpClient.Connect([System.Net.IPAddress]::Broadcast, 9)
            $BytesSent = $UdpClient.Send($MagicPacket, $MagicPacket.Length)
            $UdpClient.Close()
            $successCount++
        } catch {
            $errorMessages += "全网广播发送失败: $_"
        }
        
        if ($successCount -gt 0) {
            return "已成功通过 $successCount 个网络接口发送唤醒请求到MAC地址: $MacAddress"
        } else {
            return "发送唤醒请求失败: $($errorMessages -join '; ')"
        }
    }
    catch {
        return "发送唤醒请求时出错: $_"
    }
}

function Format-MacAddress {
    param (
        [string]$MacAddress
    )
    
    # 移除所有分隔符
    $MacAddress = $MacAddress -replace "[:-]", ""
    
    # 如果长度为12，则格式化为标准格式 (XX:XX:XX:XX:XX:XX)
    if ($MacAddress.Length -eq 12) {
        $formattedMac = ""
        for ($i = 0; $i -lt 12; $i += 2) {
            $formattedMac += $MacAddress.Substring($i, 2)
            if ($i -lt 10) {
                $formattedMac += ":"
            }
        }
        return $formattedMac
    }
    
    return $MacAddress
}

# 保存设备列表到JSON文件
function Save-DeviceList {
    param (
        [Parameter(Mandatory=$true)]
        [System.Collections.ArrayList]$Devices
    )
    
    # 确保使用绝对路径 - 兼容exe打包
    $scriptPath = $PSScriptRoot
    if ([string]::IsNullOrEmpty($scriptPath)) {
        # 如果是exe打包，使用exe所在目录
        try {
            $scriptPath = Split-Path -Parent $MyInvocation.PSCommandPath
        } catch {
            $scriptPath = $null
        }
        if ([string]::IsNullOrEmpty($scriptPath)) {
            $scriptPath = (Get-Location).Path
        }
    }
    
    # 尝试多个可能的路径
    $possiblePaths = @(
        (Join-Path -Path $scriptPath -ChildPath "WOL-Devices.json"),
        ".\WOL-Devices.json",
        (Join-Path -Path (Get-Location).Path -ChildPath "WOL-Devices.json")
    )
    
    $configPath = $null
    foreach ($path in $possiblePaths) {
        if (Test-Path -Path (Split-Path -Parent $path) -ErrorAction SilentlyContinue) {
            $configPath = $path
            break
        }
    }
    
    if (-not $configPath) {
        $configPath = Join-Path -Path $scriptPath -ChildPath "WOL-Devices.json"
    }
    
    try {
        # 确保输出目录存在
        $directory = Split-Path -Path $configPath -Parent
        if (-not (Test-Path -Path $directory)) {
            New-Item -Path $directory -ItemType Directory -Force | Out-Null
        }
        
        # 保存设备列表到JSON文件
        $Devices | ConvertTo-Json -Depth 10 | Out-File -FilePath $configPath -Encoding UTF8 -Force
        # Write-Host "设备列表已保存到: $configPath"
        return $true
    }
    catch {
        # Write-Error "保存设备列表失败: $_"
        return $false
    }
}

# 从JSON文件加载设备列表

function Load-DeviceList {
    
    
    # 确保使用绝对路径 - 兼容exe打包
    $scriptPath = $PSScriptRoot
    if ([string]::IsNullOrEmpty($scriptPath)) {
        # 如果是exe打包，使用exe所在目录
        try {
            $scriptPath = Split-Path -Parent $MyInvocation.PSCommandPath
        } catch {
            $scriptPath = $null
        }
        if ([string]::IsNullOrEmpty($scriptPath)) {
            $scriptPath = (Get-Location).Path
        }
    }
    
    # 尝试多个可能的路径
    $possiblePaths = @(
        (Join-Path -Path $scriptPath -ChildPath "WOL-Devices.json"),
        ".\WOL-Devices.json",
        (Join-Path -Path (Get-Location).Path -ChildPath "WOL-Devices.json")
    )
    
    $configPath = $null
    foreach ($path in $possiblePaths) {
        if (Test-Path -Path $path) {
            $configPath = $path
            break
        }
    }
    
    if (-not $configPath) {
        $configPath = Join-Path -Path $scriptPath -ChildPath "WOL-Devices.json"
    }
    
    $deviceList = [System.Collections.ArrayList]::new()
    
    # 调试信息 - 在exe中显示路径信息
    # $statusLabel.Text = "正在查找配置文件: $configPath"
    
    if (Test-Path -Path $configPath) {
        try {
            $devices = Get-Content -Path $configPath -Raw -Encoding UTF8 | ConvertFrom-Json
            if ($devices) {
                # 处理单个对象或数组
                if ($devices -is [array]) {
                    foreach ($device in $devices) {
                        $deviceObj = [PSCustomObject]@{
                            Name = $device.Name
                            MacAddress = $device.MacAddress
                            LastWakeTime = $device.LastWakeTime
                        }
                        [void]$deviceList.Add($deviceObj)
                    }
                } else {
                    # 单个对象
                    $deviceObj = [PSCustomObject]@{
                        Name = $devices.Name
                        MacAddress = $devices.MacAddress
                        LastWakeTime = $devices.LastWakeTime
                    }
                    [void]$deviceList.Add($deviceObj)
                }
            }
            # Write-Host "已从 $configPath 加载设备列表，共 $($deviceList.Count) 个设备"
        } catch {
            # Write-Warning "加载设备列表失败: $_"
        }
    } else {
        # Write-Host "设备列表文件不存在，将在保存时创建: $configPath"
    }

    
    return $deviceList
}

function Show-WolGUI {
    Add-Type -AssemblyName System.Windows.Forms
    Add-Type -AssemblyName System.Drawing
    
    # 初始化全局变量
    $loadedDevices = Load-DeviceList
    if ($null -eq $loadedDevices) {
        $global:SavedDevices = [System.Collections.ArrayList]::new()
    } else {
        $global:SavedDevices = [System.Collections.ArrayList]::new()
        foreach ($device in $loadedDevices) {
            [void]$global:SavedDevices.Add($device)
        }
    }
    
    # 初始化设备下拉框的函数
    function Initialize-DeviceComboBox {
        $savedDeviceComboBox.Items.Clear()
        foreach ($device in $global:SavedDevices) {
            [void]$savedDeviceComboBox.Items.Add($device)
        }
        
        if ($global:SavedDevices.Count -gt 0) {
            $savedDeviceComboBox.SelectedIndex = 0
            $statusLabel.Text = "已加载 $($global:SavedDevices.Count) 个已保存的设备"
            $statusLabel.ForeColor = [System.Drawing.Color]::Green
        } else {
            $statusLabel.Text = "没有已保存的设备，请先保存一个设备"
            $statusLabel.ForeColor = [System.Drawing.Color]::Orange
        }
    }
    
    # 创建主窗体
    $form = New-Object System.Windows.Forms.Form
    $form.Text = "局域网唤醒工具 (Wake-on-LAN)"
    $form.Size = New-Object System.Drawing.Size(600, 500)
    $form.StartPosition = "CenterScreen"
    $form.FormBorderStyle = "FixedDialog"
    $form.MaximizeBox = $false
    
    # 创建标题标签
    $titleLabel = New-Object System.Windows.Forms.Label
    $titleLabel.Location = New-Object System.Drawing.Point(20, 20)
    $titleLabel.Size = New-Object System.Drawing.Size(400, 30)
    $titleLabel.Text = "局域网唤醒工具 (Wake-on-LAN)"
    $titleLabel.Font = New-Object System.Drawing.Font("Microsoft YaHei", 14, [System.Drawing.FontStyle]::Bold)
    $form.Controls.Add($titleLabel)
    
    # 创建说明标签
    $descLabel = New-Object System.Windows.Forms.Label
    $descLabel.Location = New-Object System.Drawing.Point(20, 60)
    $descLabel.Size = New-Object System.Drawing.Size(400, 40)
    $descLabel.Text = "请输入目标设备的MAC地址，支持以下格式：`n00:11:22:33:44:55, 00-11-22-33-44-55, 或 001122334455"
    $form.Controls.Add($descLabel)
    
    # 创建MAC地址输入标签
    $macLabel = New-Object System.Windows.Forms.Label
    $macLabel.Location = New-Object System.Drawing.Point(20, 110)
    $macLabel.Size = New-Object System.Drawing.Size(100, 20)
    $macLabel.Text = "MAC地址:"
    $form.Controls.Add($macLabel)
    
    # 创建MAC地址输入框
    $macTextBox = New-Object System.Windows.Forms.TextBox
    $macTextBox.Location = New-Object System.Drawing.Point(120, 110)
    $macTextBox.Size = New-Object System.Drawing.Size(200, 20)
    $form.Controls.Add($macTextBox)
    
    # 创建格式化按钮
    $formatButton = New-Object System.Windows.Forms.Button
    $formatButton.Location = New-Object System.Drawing.Point(330, 110)
    $formatButton.Size = New-Object System.Drawing.Size(80, 23)
    $formatButton.Text = "格式化"
    $formatButton.Add_Click({
        $macTextBox.Text = Format-MacAddress -MacAddress $macTextBox.Text
    })
    $form.Controls.Add($formatButton)
    
    # 创建设备名称标签（可选）
    $deviceLabel = New-Object System.Windows.Forms.Label
    $deviceLabel.Location = New-Object System.Drawing.Point(20, 150)
    $deviceLabel.Size = New-Object System.Drawing.Size(100, 20)
    $deviceLabel.Text = "设备名称:"
    $form.Controls.Add($deviceLabel)
    
    # 创建设备名称输入框（可选）
    $deviceTextBox = New-Object System.Windows.Forms.TextBox
    $deviceTextBox.Location = New-Object System.Drawing.Point(120, 150)
    $deviceTextBox.Size = New-Object System.Drawing.Size(200, 20)
    $deviceTextBox.Text = "我的电脑"
    $form.Controls.Add($deviceTextBox)
    
    # 创建已保存设备选择标签
    $savedDeviceLabel = New-Object System.Windows.Forms.Label
    $savedDeviceLabel.Location = New-Object System.Drawing.Point(20, 180)
    $savedDeviceLabel.Size = New-Object System.Drawing.Size(100, 20)
    $savedDeviceLabel.Text = "已保存设备:"
    $form.Controls.Add($savedDeviceLabel)
    
    # 创建已保存设备下拉框
    $savedDeviceComboBox = New-Object System.Windows.Forms.ComboBox
    $savedDeviceComboBox.Location = New-Object System.Drawing.Point(120, 180)
    $savedDeviceComboBox.Size = New-Object System.Drawing.Size(200, 20)
    $savedDeviceComboBox.DropDownStyle = [System.Windows.Forms.ComboBoxStyle]::DropDownList
    $form.Controls.Add($savedDeviceComboBox)
    
    # 创建加载设备按钮
    $loadDeviceButton = New-Object System.Windows.Forms.Button
    $loadDeviceButton.Location = New-Object System.Drawing.Point(330, 180)
    $loadDeviceButton.Size = New-Object System.Drawing.Size(80, 23)
    $loadDeviceButton.Text = "加载设备"
    $loadDeviceButton.Add_Click({
        if ($savedDeviceComboBox.SelectedItem) {
            $selectedDevice = $savedDeviceComboBox.SelectedItem
            $macTextBox.Text = $selectedDevice.MacAddress
            $deviceTextBox.Text = $selectedDevice.Name
            $statusLabel.Text = "已加载设备: $($selectedDevice.Name)"
            $statusLabel.ForeColor = [System.Drawing.Color]::Green
        }
    })
    $form.Controls.Add($loadDeviceButton)
    
    # 创建刷新设备列表按钮
    $refreshDeviceButton = New-Object System.Windows.Forms.Button
    $refreshDeviceButton.Location = New-Object System.Drawing.Point(420, 180)
    $refreshDeviceButton.Size = New-Object System.Drawing.Size(60, 23)
    $refreshDeviceButton.Text = "刷新"
    $refreshDeviceButton.Add_Click({
        # 重新加载设备列表
        $global:SavedDevices = Load-DeviceList
        if ($null -eq $global:SavedDevices) {
            $global:SavedDevices = [System.Collections.ArrayList]::new()
        }
        
        # 更新下拉框
        $savedDeviceComboBox.Items.Clear()
        foreach ($device in $global:SavedDevices) {
            [void]$savedDeviceComboBox.Items.Add($device)
        }
        
        if ($global:SavedDevices.Count -gt 0) {
            $savedDeviceComboBox.SelectedIndex = 0
            $statusLabel.Text = "已刷新设备列表，共 $($global:SavedDevices.Count) 个设备"
            $statusLabel.ForeColor = [System.Drawing.Color]::Green
        } else {
            $statusLabel.Text = "没有已保存的设备"
            $statusLabel.ForeColor = [System.Drawing.Color]::Orange
        }
    })
    $form.Controls.Add($refreshDeviceButton)
    
    # 创建保存按钮
    $saveButton = New-Object System.Windows.Forms.Button
    $saveButton.Location = New-Object System.Drawing.Point(330, 150)
    $saveButton.Size = New-Object System.Drawing.Size(80, 23)
    $saveButton.Text = "保存设备"
    $saveButton.Add_Click({
        $mac = $macTextBox.Text
        $deviceName = $deviceTextBox.Text
        
        if ([string]::IsNullOrWhiteSpace($mac)) {
            $statusLabel.Text = "错误: 请输入MAC地址"
            $statusLabel.ForeColor = [System.Drawing.Color]::Red
            return
        }
        
        if ([string]::IsNullOrWhiteSpace($deviceName)) {
            $deviceName = "未命名设备"
        }
        
        # 检查MAC地址格式
        $MacRegex = "^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$|^([0-9A-Fa-f]{12})$"
        if (-not ($mac -match $MacRegex)) {
            $statusLabel.Text = "错误: 无效的MAC地址格式"
            $statusLabel.ForeColor = [System.Drawing.Color]::Red
            return
        }
        
        # 格式化MAC地址
        $mac = Format-MacAddress -MacAddress $mac
        
        # 检查是否已存在
        $existingDevice = $null
        foreach ($device in $global:SavedDevices) {
            if ($device.MacAddress -eq $mac) {
                $existingDevice = $device
                break
            }
        }
        
        if ($existingDevice) {
            $existingDevice.Name = $deviceName
            $existingDevice.LastWakeTime = [DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss")
        } else {
            # 添加到保存列表
            $device = [PSCustomObject]@{
                Name = $deviceName
                MacAddress = $mac
                LastWakeTime = [DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss")
            }
            [void]$global:SavedDevices.Add($device)
        }
        
        # 保存设备列表
        $saveResult = Save-DeviceList -Devices $global:SavedDevices
        if ($saveResult) {
            $statusLabel.Text = "已保存设备: $deviceName ($mac)"
            $statusLabel.ForeColor = [System.Drawing.Color]::Green
            
            # 刷新设备下拉框
            $savedDeviceComboBox.Items.Clear()
            foreach ($device in $global:SavedDevices) {
                [void]$savedDeviceComboBox.Items.Add($device)
            }
            $savedDeviceComboBox.SelectedIndex = $global:SavedDevices.Count - 1
        } else {
            $statusLabel.Text = "保存设备失败"
            $statusLabel.ForeColor = [System.Drawing.Color]::Red
        }
    })
    $form.Controls.Add($saveButton)
    
    # 创建唤醒按钮
    $wakeButton = New-Object System.Windows.Forms.Button
    $wakeButton.Location = New-Object System.Drawing.Point(120, 220)
    $wakeButton.Size = New-Object System.Drawing.Size(200, 30)
    $wakeButton.Text = "唤醒设备"
    $wakeButton.BackColor = [System.Drawing.Color]::FromArgb(0, 120, 215)
    $wakeButton.ForeColor = [System.Drawing.Color]::White
    $wakeButton.FlatStyle = [System.Windows.Forms.FlatStyle]::Flat
    $wakeButton.Add_Click({
        $mac = $macTextBox.Text
        if ([string]::IsNullOrWhiteSpace($mac)) {
            $statusLabel.Text = "错误: 请输入MAC地址"
            $statusLabel.ForeColor = [System.Drawing.Color]::Red
            return
        }
        
        $result = Send-WOL -MacAddress $mac
        if ($result.StartsWith("已成功")) {
            $statusLabel.Text = $result
            $statusLabel.ForeColor = [System.Drawing.Color]::Green
            
            # 添加到历史记录
            $deviceName = $deviceTextBox.Text
            if ([string]::IsNullOrWhiteSpace($deviceName)) {
                $deviceName = "未命名设备"
            }
            
            $item = New-Object System.Windows.Forms.ListViewItem($deviceName)
            [void]$item.SubItems.Add($mac)
            [void]$item.SubItems.Add([DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss"))
            [void]$historyListView.Items.Add($item)
        } else {
            $statusLabel.Text = $result
            $statusLabel.ForeColor = [System.Drawing.Color]::Red
        }
    })
    $form.Controls.Add($wakeButton)
    
    # 创建状态标签
    $statusLabel = New-Object System.Windows.Forms.Label
    $statusLabel.Location = New-Object System.Drawing.Point(20, 260)
    $statusLabel.Size = New-Object System.Drawing.Size(400, 20)
    $statusLabel.Text = "准备就绪"
    $form.Controls.Add($statusLabel)
    
    # 创建历史记录标签
    $historyLabel = New-Object System.Windows.Forms.Label
    $historyLabel.Location = New-Object System.Drawing.Point(20, 290)
    $historyLabel.Size = New-Object System.Drawing.Size(100, 20)
    $historyLabel.Text = "历史记录:"
    $form.Controls.Add($historyLabel)
    
    # 创建历史记录列表
    $historyListView = New-Object System.Windows.Forms.ListView
    $historyListView.Location = New-Object System.Drawing.Point(20, 310)
    $historyListView.Size = New-Object System.Drawing.Size(400, 100)
    $historyListView.View = [System.Windows.Forms.View]::Details
    $historyListView.FullRowSelect = $true
    $historyListView.GridLines = $true
    
    # 添加列
    $historyListView.Columns.Add("设备名称", 120) | Out-Null
    $historyListView.Columns.Add("MAC地址", 150) | Out-Null
    $historyListView.Columns.Add("时间", 120) | Out-Null
    
    # 添加右键菜单
    $contextMenu = New-Object System.Windows.Forms.ContextMenuStrip
    $reWakeItem = $contextMenu.Items.Add("重新唤醒")
    $reWakeItem.Add_Click({
        if ($historyListView.SelectedItems.Count -gt 0) {
            $mac = $historyListView.SelectedItems[0].SubItems[1].Text
            $macTextBox.Text = $mac
            $deviceTextBox.Text = $historyListView.SelectedItems[0].Text
            $result = Send-WOL -MacAddress $mac
            $statusLabel.Text = $result
            if ($result.StartsWith("已成功")) {
                $statusLabel.ForeColor = [System.Drawing.Color]::Green
            } else {
                $statusLabel.ForeColor = [System.Drawing.Color]::Red
            }
        }
    })
    $historyListView.ContextMenuStrip = $contextMenu
    
    $form.Controls.Add($historyListView)
    
    # 调整窗体大小以适应历史记录列表
    $form.Size = New-Object System.Drawing.Size(500, 450)
    
    # 初始化设备下拉框
    Initialize-DeviceComboBox
    
    # 自动加载最近使用的设备（如果有的话）
    if ($global:SavedDevices.Count -gt 0) {
        try {
            # 按最后唤醒时间排序，获取最近使用的设备
            $sortedDevices = $global:SavedDevices | Sort-Object { 
                try {
                    [DateTime]::ParseExact($_.LastWakeTime, "yyyy-MM-dd HH:mm:ss", $null)
                } catch {
                    [DateTime]::MinValue
                }
            } -Descending
            
            $lastUsedDevice = $sortedDevices[0]
            
            $macTextBox.Text = $lastUsedDevice.MacAddress
            $deviceTextBox.Text = $lastUsedDevice.Name
            
            # 在下拉框中找到对应的设备并选中
            for ($i = 0; $i -lt $savedDeviceComboBox.Items.Count; $i++) {
                if ($savedDeviceComboBox.Items[$i].MacAddress -eq $lastUsedDevice.MacAddress) {
                    $savedDeviceComboBox.SelectedIndex = $i
                    break
                }
            }
            
            $statusLabel.Text = "已自动加载最近使用的设备: $($lastUsedDevice.Name)"
            $statusLabel.ForeColor = [System.Drawing.Color]::Green
        } catch {
            # 如果排序失败，就加载第一个设备
            $firstDevice = $global:SavedDevices[0]
            $macTextBox.Text = $firstDevice.MacAddress
            $deviceTextBox.Text = $firstDevice.Name
            $savedDeviceComboBox.SelectedIndex = 0
            $statusLabel.Text = "已自动加载设备: $($firstDevice.Name)"
            $statusLabel.ForeColor = [System.Drawing.Color]::Green
        }
    } else {
        $statusLabel.Text = "没有已保存的设备，请先保存一个设备"
        $statusLabel.ForeColor = [System.Drawing.Color]::Orange
    }
    
    # 显示窗体
    # $form.ShowDialog() | Out-Null
    [void]$form.ShowDialog() 
}

# 主程序逻辑
if ($GUI -or (-not $PSBoundParameters.ContainsKey('MacAddress'))) {
    # 启动图形界面
    Show-WolGUI
} else {
    # 命令行模式
    $result = Send-WOL -MacAddress $MacAddress
    if ($result.StartsWith("已成功")) {
        # Write-Host $result -ForegroundColor Green
        return
    } else {
        # Write-Error $result
        return
    }
}